/**
 * file 转Base64 DataURL
 * @param {File} file
 * @returns
 */
export function fileToBase64Async(file:File,callback:(url:string)=>void) {

        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e)=>{
            if(e.target && typeof e.target.result === "string"){
                callback( e.target.result )
                return
            }
            callback( "")
        }

}
/**
 * file 转Base64 DataURL
 * @param {File} file
 * @returns
 */

/**
 * 解析base64中的数据信息
 * @param {String} base64
 * @returns
 */
function parseBase64(base64:any) {
    const arr = base64.split(","),
        mime = arr[0].match(/:(.*?);/)[1];

    return {
        mime,
        data: arr[1],
    };
}

/**
 * base64转Uint8
 * @param {String} base64
 * @returns
 */
function base64ToUint8Array(base64:string) {
    const parsedBase64 = parseBase64(base64);

    const bstr = atob(parsedBase64.data);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }

    return u8arr;
}

/**
 * 将base64转换为blob
 * @param {String} base64
 * @returns
 */
function base64ToBlob(base64:string) {
    const parsedBase64 = parseBase64(base64);
    const u8arr = base64ToUint8Array(base64);
    return new Blob([u8arr], { type: parsedBase64.mime });
}

/**
 * 将blob转换为file
 * @param {Blob} blobData
 * @returns
 */
function blobToFile(blobData:any) {
    const date = new Date();

    blobData.lastModifiedDate = date;
    blobData.lastModified = date.getTime();
    blobData.name = blobData.type.replace("/", ".");

    return blobData;
}

/**
 * base64 转 File
 * @param {String} base64
 * @returns
 */
export function base64ToFile(base64: string) {
    let file = null;

    // 浏览器兼容
    if (window.File != undefined) {
        const parsedBase64 = parseBase64(base64);
        const u8arr = base64ToUint8Array(base64);
        file = new File([u8arr], parsedBase64.mime.replace("/", "."), {
            type: parsedBase64.mime,
        });
    } else {
        file = blobToFile(base64ToBlob(base64));
    }

    return file;
}




export function blobToDataURI(blob:Blob, callback:Function) {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = function (e) {
        if(!e.target){
            callback("")
            return
        }
        callback(e.target.result);
    }
}